<?php

namespace App\Http\Controllers\Service;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Repositories\GameServer\OrderRepository;
use App\Repositories\GameServer\GoodsRepository;
use App\Repositories\GamerRepository;
use App\Repositories\GameServer\RechargeRecordRepository;
use App\Models\GameServer\Order;
use Carbon\Carbon;
use Redis;

use App\Http\Controllers\Service\IapppayConfig as Config;
use App\Http\Controllers\Service\IapppayUtil as Util;


class IapppayController extends Controller
{
    private $orderUrl = 'http://ipay.iapppay.com:9999/payapi/order';
    private $getwayUrl = 'https://web.iapppay.com/pay/gateway?';

    protected $Order;
    protected $Goods;
    protected $Gamer;

    public function __construct(OrderRepository $order, GoodsRepository $goods, GamerRepository $gamer)
    {
        $this->Order = $order;
        $this->Goods = $goods;
        $this->Gamer = $gamer;

    }

    /**
     * 创建订单
     * @param  Request $request [description]
     * @return string           收银台url
     */
    public function order(Request $request)
    {
        if (empty($request->goods_id)) {
            return json_encode(['status' => 1, 'msg' => '商品信息错误']);
        }

        if (empty($request->gamer_id)) {
            return json_encode(['status' => 2, 'msg' => '玩家信息错误']);
        }

        $goods_id = $request->goods_id;
        $gamer_id = $request->gamer_id;

        //查询该用户是否有未支付订单
        $order = $this->Order->getOrderByGamerId($goods_id, $gamer_id);

        if ($order) {
            $deadline = $order->created_at->addMinutes(25);
            $now = Carbon::now();

            if ($deadline < $now) {//订单已过期,无效则删除,重新下单
                $this->Order->deleteOrder($order->id);
                $transid = $this->createOrder($goods_id, $gamer_id);
            }
            else {
                $transid = $order->transid;
            }
        }
        else {
            $transid = $this->createOrder($goods_id, $gamer_id);
        }

        $payUrl = $this->getUrl($transid);
        echo $payUrl;

        // header('Access-Control-Allow-Origin: *');
        // header('location: ' . $payUrl);

    }

    //创建订单
    public function createOrder($goods_id, $gamer_id)
    {
        $order = $this->Order->recharge($goods_id, $gamer_id);
        $transid = $this->iapppayOrder($order);

        if ($transid === false) {
            // $this->Order->deleteOrder($order->id);

            echo json_encode(['status' => 3, 'msg' => '流水订单创建失败']);
            exit();
        }

        $this->Order->setTransid($order, $transid);

        return $transid;
    }

    //爱贝支付创建订单
    public function iapppayOrder(Order $order)
    {
        $Util = new Util();
        $data = [
            'appid' => Config::APPID,
            'waresid' => $order->product_no,
            'waresname' => $order->goods_name,
            'cporderid' => $order->order_no,
            'price' => $order->goods_price,
            'currency' => 'RMB',
            'appuserid' => (string)$order->gamer_id,
            'notifyurl' => route('iapppay.notify')
        ];
        $req_data = $Util->composeReq($data, Config::APPKEY);

        $order_url = $this->orderUrl;
        $resp_data = $Util->request_by_curl($order_url, $req_data, 'For IAppPay');


        //验签数据并且解析返回报文
        if(!$Util->parseResp($resp_data, Config::PLATPKEY, $respJson)) {
            return false;
        }else{

            //下单成功之后获取 transid
            $transid=$respJson->transid;
        }

        return $transid;
    }

    public function getUrl($transid)
    {
        $Util = new Util();
        $getwayUrl = $this->getwayUrl;
        $data = [
            'tid' => $transid,
            'app' => Config::APPID,
            'url_r' => 'http://www.baidu.com', //支付成功回调url地址
            'url_h' => 'http://www.qq.com' //返回商户url地址
        ];
        $req_data = $Util->h5composeReq($data, Config::APPKEY);

        return $getwayUrl . $req_data;
    }

    //支付订单
    public function pay()
    {

    }

    //回调地址
    public function notify(Request $request, RechargeRecordRepository $recharge)
    {
        $data = $request->transdata;

        if (stripos('%22', $data)) {
            $data = array_map('urldecode', $data);
        }

        $data = json_decode($data, true);

        $order_no = $data['cporderid'];
        $order = $this->Order->getOrder($order_no);

        if ($order->status == 1) {
            echo 'SUCCESS';exit;
        }

        //支付成功
        if ($data['result'] === 0) {
            $goods = $this->Goods->getGoods($order->goods_id);
            $gamer = $this->Gamer->getGamer($order->gamer_id);

            $params = [
                'actual_price' => $data['money'],
                'trans_time' => $data['transtime'],
                'paytype' => $data['paytype'],
                'status' => 1,
                'distributer_id' => $gamer->distributer_id
            ];

            $vip_score = $data['money'] > 1 ? $data['money'] : 1;

            //修改玩家筹码
            $jeton = Redis::hincrby($gamer->account_name, 'jeton', $goods->gold + $goods->gift_gold);
            $vip_score = Redis::hincrby($gamer->account_name, 'vip_score', $vip_score);
            $this->Gamer->patchGamer($order->gamer_id, ['jeton' => $goods->gold + $goods->gift_gold]);

            //增加充值记录
            $record = [
                'account_id' => $gamer->id,
                'account_name' => $gamer->nickname,
                'price' => $data['money'],
                'jeton' => $goods->gold,
                'gift_jeton' => $goods->gift_gold,
                'item_id' => $goods->id,
                'item_name' => $goods->item_name,
                'buy_time' => Carbon::now()->toDateTimeString(),
                'note' => $goods->note,
                'total_jeton' => $jeton
            ];
            $recharge_record = $recharge->addRechargeRecord($record);

        }
        else {
            $params = [
                'status' => 2,
                'paytype' => $data['paytype']
            ];
        }

        $res = $this->Order->updateOrder($order_no, $params);

        echo 'SUCCESS';

    }
}
